/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servidor.rmi;

import java.rmi.RemoteException;
import servidor.auxiliar.DataCliente;
import servidor.auxiliar.GereServer;

/**
 *
 * @author ziza
 */
public class RMIConexao implements Runnable {

    Thread corre;
    boolean running = true;
    RMIservice metodos;
    GereServer gestor;
    int i=0;

    public RMIConexao(RMIservice metodos, GereServer gestor) {
        this.gestor = gestor;
        corre = new Thread(this);
        this.metodos = metodos;
        corre.start();
    }

    public void run() {
        int erro = 0;
        while (running) {
            erro = metodos.startService();
            if (erro != 0) {
                System.out.println("Falha ligacao!!!");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException ex) {
                }
                System.out.println("Tenta de Novo!!!");
                continue;
            }
            while (erro == 0) {
                System.out.println("Servidor ligada!!!");
                synchronized (this) {
                    try {
                        Thread.sleep(10000);
                        if(gestor.getClientes().getOnline().size()>0){
                            DataCliente cliente=gestor.efectuaPing();
                            while(cliente!=null && i<gestor.getClientes().getOnline().size()){
                                try {
                                    i++;
                                    if(cliente.getLigacao()!=null){
                                        String resp = cliente.getLigacao().ping();
                                        if(resp.equals("ok"))
                                            System.out.println("Resposta:"+resp);
                                    }
                                } catch (RemoteException ex) {
                                    gestor.getClientes().desliga(cliente);
                                    System.out.println("Cliente removido!!!");
                                }
                            }
                            i=0;
                        }                 
                    } catch (InterruptedException ex) {
                    }
                }
            }
        }
    }
}

